#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import ConfigParser
import re

from abstract import *
from parseemail import *
from synsheets  import *



config = ConfigParser.ConfigParser()
config.read("D:\Emails\config\mail.cfg")


hostname = config.get('server', 'hostname')
username = config.get('account', 'username')
password = config.get('account', 'password')
server_port = 993

m = imaplib.IMAP4_SSL(hostname,server_port)
m.login(username, password)
m.select('INBOX',readonly=True)

typ,data = m.search(None,'UNSEEN')


unreaduid = data[0].split()

trans = {}
count_i = 0
date_dict = {'Jan':'01',
             'Feb':'02',
             'Mar':'03',
             'Apr':'04',
             'May':'05',
             'Jun':'06',
             'Jul':'07',
             'Aug':'08',
             'Sep':'09',
             'Oct':'10',
             'Nov':'11',
             'Dec':'12'
             }


def decode_subject(subject):
    #解码邮件的主题，subject 应为 编码为utf-8的字符串
    #此函数对邮件主题进行解码，争议的状态，根据情况，分析出争议的类型
    result = { 'status':'',  'reason':''}
    refund_word = ["要求",
            "Request",
            "升级",
            "Escalated",
            "调查付款撤销"
            ]
    #要先搜索dispute_word中的词语，因为refund_word中是最新状态
    dispute_word = ["争议",
            "新的",
            "新消息"
            "Dispute",
            "dispute",
            "New"
            ]
    no_reciept_word = ["物品未收到",
                "Recived"
                ]
    not_as_desc = ["与描述显著不符",
                "Described"
                ]
    unauthorised = ["调查付款撤销"]
    #扫描邮件主题，有可能获得争议原因信息
    for i in no_reciept_word :
        if subject.find(i) != -1 :
            result['reason'] = '未收到'
            break
    for i in not_as_desc :
        if subject.find(i) != -1 :
            result['reason'] = '与描述不相符'
            break
    for i in unauthorised :
        if subject.find(i) != -1 :
            result['reason'] = '未经授权'
            break

    #扫描邮件主题，有可能更新投诉类型信息
    for i in dispute_word :
        if subject.find(i) != -1 :
            result['status'] = '争议'
            break
    for i in refund_word :
        if subject.find(i) != -1 :
            result['status'] = '补偿请求'
            break

    return result

def decode_date (date):
    date_dict = {'Jan':'01',
                 'Feb':'02',
                 'Mar':'03',
                 'Apr':'04',
                 'May':'05',
                 'Jun':'06',
                 'Jul':'07',
                 'Aug':'08',
                 'Sep':'09',
                 'Oct':'10',
                 'Nov':'11',
                 'Dec':'12'
                 }
    #解码邮件中的日期，转换问形如 2011-9-6的形式
    match_date = re.match(r"^\w{3},\s(\d{1,2})\s(\w{3})\s(\d{4})",date)
    if match_date :
        temp = list(match_date.groups())
        mon = date_dict[temp[1]]
        temp[1] = mon
        temp.reverse()
        date = '-'.join(temp)

    return date



for email_id in unreaduid:
    print "2 get email %s .." % email_id
    resp, data = m.fetch(email_id,'(RFC822)')
    body =  email.message_from_string(data[0][1])
    from_addr = body['From']
    raw_date    = body['Date']
    raw_subject = body['Subject']
    print raw_date
    #转换日期为excel能识别的格式
    date = decode_date(raw_date)
    #只处理来自paypal的邮件
    match1  = re.match(r".*service@intl.paypal.com",from_addr)
    re_case = re.compile(r'.*(PP-\d{3}-\d{3}-\d{3}-\d{3})')
    if match1 :
        #如果是来自paypal的邮件，
        #在网易企业邮上面不能置为已读
        m.store(email_id,'+FLAGS','\SEEN')
        match2 = re_case.match(raw_subject)
        if match2 :
            whole_body = get_mail_contents(body)

            for part in whole_body :
                if part.is_body == 'text/plain' :
                    payload, used_charset = decode_text(part.payload,part.charset,'auto')
                    break
            print "解码为:%s"%used_charset
            try :
                subject_code = raw_subject.decode(used_charset).encode('utf8')
            except UnicodeError :
                subject_code = raw_subject
            info = payload.encode('utf8')
            if used_charset == 'gb2312' :
                lang = 'ch'
            else :
                lang = 'en'
            trans = abstract_tran_info(info, lang)
            if not trans['case_id'] :
                trans['case_id'] = match2.groups()[0]
            trans['date'] = date
            #解码主题
            temp = decode_subject(subject_code)
            trans['reason'] = temp['reason']
            trans['status'] = temp['status']

            #解码过程信息
            #TODO
            trans['process']= subject_code

            print trans
            synsheets(trans)
            #跟新后标记为已读信件

            count_i += 1
            if count_i == 99 :
                break